home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Pascal Super Library
/
Pascal Super Library (CW International)(1997).bin
/
LIBRARY
/
CMPLTPAS
/
KSEARCH.PAS
< prev
next >
Wrap
Pascal/Delphi Source File
|
1988-07-24
|
3KB
|
61 lines
{->>>>KeySearch<<<<--------------------------------------------}
{ }
{ Filename : KSEARCH.SRC -- Last Modified 7/14/88 }
{ }
{ This routine searches file Keys for key records containing }
{ the key string contained in parameter MatchIt. The method }
{ is your classic binary search, and the key record type is }
{ defined as the type show below: }
{ }
{ KeyRec = RECORD }
{ Ref : Integer; }
{ KeyData : String30 }
{ END; }
{ }
{ The function returns True if a matching record is found, }
{ else False. }
{ }
{ From: COMPLETE TURBO PASCAL 5.0 by Jeff Duntemann }
{ Scott, Foresman & Co., Inc. 1988 ISBN 0-673-38355-5 }
{--------------------------------------------------------------}
FUNCTION KeySearch(VAR Keys : KeyFile;
VAR KeyRef : Integer;
MatchIt : String80) : Boolean;
VAR High,Low,Mid : Integer;
SearchRec : KeyRec;
Found : Boolean;
Collided : Boolean;
RecCount : Integer;
BEGIN
KeyRef := 0; { Initialize variables }
RecCount := FileSize(Keys);
High := RecCount;
Low := 0;
KeySearch := False; Found := False; Collided := False;
Mid := (Low + High) DIV 2; { Calc first midpoint }
IF RecCount > 0 THEN { Don't search if file empty}
REPEAT
Seek(Keys,Mid); { Read midpoint record }
Read(Keys,SearchRec);
{ Collision between Mid & Low or Mid & High? }
IF (Low = Mid) OR (High = Mid) THEN Collided := True;
IF MatchIt = SearchRec.KeyData THEN { Found it! }
BEGIN
Found := True; { Set found flag... }
KeySearch := True; { ...function value... }
KeyRef := SearchRec.Ref { ...and file key }
END
ELSE { No luck...divide & try again }
BEGIN
IF MatchIt > SearchRec.KeyData THEN Low := Mid
ELSE High := Mid; { Halve the field }
Mid := (Low + High + 1) DIV 2; { Recalc midpoint }
KeyRef := Mid { Save Mid in parm }
END
UNTIL Collided OR Found
END;